package cms.util;

import cms.common.SqlSessionAndMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


/**
 * @ClassName: SqlSessionUtil.java
 * @author: yuhui
 * @version: 1.0.0
 * @Description: TODO
 * @createTime: 2021年04月13日 19:16:00
 */
public class SqlSessionUtil {
    private static final SqlSessionFactory sqlFaction;

    static{
        SqlSessionFactoryBuilder sqlBuilder = null;
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream("mybatis.xml"); //引入mybatis核心配置文件
            sqlBuilder = new SqlSessionFactoryBuilder(); //创建SqlSessionFactoryBuilder
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlFaction = sqlBuilder.build(in); //解析配置文件
    }

    /**
     * @title: createSqlSession
     * @description: 创建sql会话
     * @author: YH 
     * @modifyTime: 2021/4/13 19:27
     */
    public static SqlSession createSqlSession(){
        SqlSession sqlSession = sqlFaction.openSession(); //生成sql会话
        return sqlSession;
    }

    public static SqlSessionAndMapper getMapper(Class cls){
        SqlSession sqlSession = createSqlSession();
        Object mapper = sqlSession.getMapper(cls);
        return new SqlSessionAndMapper(mapper,sqlSession);
    }

    public static void commitAndclose(SqlSession sqlsession){
        sqlsession.commit();
        sqlsession.close();
    }
}
